package com.bowos.zmado.service;

import org.springframework.stereotype.Service;

import com.bowos.utils.SpringUtils;
import com.bowos.zmado.dao.UserDao;
import com.bowos.zmado.model.User;
import com.orifine.web.ActionFrom;
import com.orifine.web.Property;
import com.orifine.web.Validator;

@Service
public class UserManager {
	private UserDao userDao;

	/**
	 * 用户注册
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param rePassword
	 *            确认密码
	 * @param email
	 *            Email
	 * @param validateCode
	 *            验证码
	 * @return 是否注册成功
	 */
	public boolean register(String username, String password, String rePassword, String email, String validateCode) {

		ActionFrom actionFrom = SpringUtils.getBean(ActionFrom.class);

		actionFrom.addValidator("username", User.columnUsername.getValidates(), username);

		actionFrom.addValidator("password", User.columnPassword.getValidates(), password);
		actionFrom.addValidator("rePassword", new Validator() {
			@Override
			protected boolean execute(Object... values) {
				String password = (String) values[0];
				String rePassword = (String) values[1];
				if (!password.equals(rePassword)) {
					return false;
				} else {
					return true;
				}
			}

			@Override
			public Property property() {
				return new Property("重复密码输入不正确");
			}
		}, password, rePassword);
		
		actionFrom.addValidator("username", new Validator() {

			@Override
			protected boolean execute(Object... values) {
				String username = (String)values[0];
				if(userDao.getUserByUsername(username) != null){
					return true;
				} else {
					return false;
				}
			}
			
			@Override
			public Property property() {
				return new Property("{0}已经存在");
			}

			@Override
			public boolean lazy() {
				return false;
			}
		}.setDomain(User.columnUsername.getActualName()), username);
		
		if(actionFrom.hasNext()){
			return false;
			//throw new RuntimeException();
		}

		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		return userDao.insertUser(user);
	}

	/**
	 * 用户登陆
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param validateCode
	 *            验证码
	 * @return 是否登陆成功
	 */
	public boolean login(String username, String password, String validateCode) {
		User user = userDao.getUserByUsername(username);
		return user.getPassword().equals(password);
	}

	/**
	 * 用户找回密码
	 * 
	 * @param username
	 * @param email
	 * @return 信息输入是否正确
	 */
	public boolean findPassword(String username, String email) {
		return false;
	}
}
